package org.vs.util;

import io.jsonwebtoken.*;
import org.vs.constant.UserConstant;
import org.vs.domain.model.SysUser;

import java.util.Date;

public class JwtUtil {
    private JwtParser parser;

    public static String getToken(SysUser user) {
        long time = System.currentTimeMillis();

        JwtBuilder jwtBuilder = Jwts.builder()
                .setId(user.getUserId().toString())
                .setSubject(user.getUsername())
                .setIssuedAt(new Date(time))
                .signWith(SignatureAlgorithm.HS256, "vote")
                .setExpiration(new Date(time + UserConstant.LOGIN_TIME));

        return jwtBuilder.compact();
    }

    public static SysUser getUser(String token) {
        Claims claims =
                Jwts.parser().setSigningKey("vote").parseClaimsJws(token).getBody();

        SysUser sysUser = SysUser
                .builder()
                .userId(Long.parseLong(claims.getId()))
                .build();

        return sysUser;
    }

    public static boolean verifyToken(String token) {
        if (token == null) {
            return false;
        }

        Claims claims =
                Jwts.parser().setSigningKey("vote").parseClaimsJws(token).getBody();
        claims.getExpiration().before(new Date());
        if (claims.getExpiration().getTime() - System.currentTimeMillis() <= 0) {
            return false;
        }

        return true;
    }
}
